﻿using System.Collections.Generic;
using Corona.TagContract;
using Corona.TagToolkit.Exception;
namespace Corona.TagToolkit
{

    public enum ResourceState
    {
        Controlled, UnControlled
    }
    /// <summary>
    /// 代表一个资源
    /// 用户应用应该继承此类，并增加对具体资源相关的操作的方法(实现ResourceHandler接口)
    /// </summary>
    /// <typeparam name="T">具体的资源，如一个文件</typeparam>
    public class Resource<T>
    {
        internal static AppSupport<T> appSupport;

        internal long uid;
        internal T value;
        private string locazier;

        public string Locazier
        {
            get { return locazier; }
        }
        private ResourceState state=ResourceState.UnControlled;

        /// <summary>
        /// 只有实现了IControllable才可被纳入系统
        /// </summary>
        public ResourceState State
        {
            get {
                if (this as IControllable != null)
                    return state;
                else
                    return ResourceState.UnControlled;
            }
        }

        public Resource() { }
        public Resource(string locazier)
        {
            SetResource(locazier);
        }

        /// <summary>
        /// 确定资源，资源将处于托管状态
        /// </summary>
        /// <param name="locazier"></param>
        public void SetResource(string locazier)
        {
            if (appSupport == null)
                throw new AppSupportNotReadyException("Resource initial failed because appSupport is null");
            appSupport.SetResource(this, locazier);
            this.state = ResourceState.Controlled;
        }

        /// <summary>
        /// 去掉强连接，此资源不再受Corona框架管辖，资源将变为非托管状态，如果本来为非托管，则没有事情发生
        /// </summary>
        public void RemoveStrongLink()
        {
            appSupport.Database.removeStrongLink(this);
            this.state = ResourceState.UnControlled;
        }
        /// <summary>
        /// 对资源的引用
        /// </summary>
        public T Value
        {
            get { return this.value; }
        }

        /// <summary>
        /// uid
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            return uid.ToString() +" "+locazier;
        }

        /// <summary>
        /// 已重载
        /// uid和T.Equal相等时相等
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public override bool Equals(object obj)
        {
            Resource<T> resource = obj as Resource<T>;
            if (resource == null)
                return false;
            else
                return this.uid == resource.uid && this.Value.Equals(resource.Value);

        }

        public override int GetHashCode()
        {
            return (int)uid ^ value.GetHashCode();
        }

    }

}
